<?php
/**
 * 基础物料控制层
 *
 * @author kamisama.xia@gmail.com
 * @version 0.1
 */

class material_ctl_admin_material_basic extends desktop_controller{

    var $workground = 'goods_manager';

    /**
     * 基础物料列表分栏菜单
     *
     * @param Null
     * @return Array
     */
    function _views(){
        $basicMaterialObj = app::get('material')->model('basic_material');
        
        $all_filter = array();
        $sale_filter = array("visibled"=>1);
        $stop_sale_filter = array("visibled"=>2);
        $on_omnichannel     = array('omnichannel'=>1);
        $off_omnichannel    = array('omnichannel'=>2);
        
        //获取供货商id
        if($_REQUEST["supplier_id"]){
            //切换点击
            $supplier_id = $_REQUEST["supplier_id"];
        }else{
            //首次入页
            if ($_REQUEST["p"][0]){
                $supplier_id = $_REQUEST["p"][0];
            }
        }
        
        if($supplier_id){
            //根据供应商，获取基础物料列表
            $oSupplierGoods = app::get('purchase')->model('supplier_goods');
            $goods_id = $oSupplierGoods->getSupplierGoods($supplier_id); 
            $all_filter["bm_id"] = $goods_id["goods_id"];
            $sale_filter["bm_id"] = $goods_id["goods_id"];
            $stop_sale_filter["bm_id"] = $goods_id["goods_id"];
            
            $on_omnichannel["bm_id"]  = $goods_id["goods_id"];
            $off_omnichannel["bm_id"] = $goods_id["goods_id"];
        }
        
        $sub_menu = array(
            0 => array('label'=>app::get('base')->_('全部'),'filter'=>$all_filter,'optional'=>false),
            1 => array('label'=>app::get('base')->_('在售'),'filter'=>$sale_filter,'optional'=>false),
            2 => array('label'=>app::get('base')->_('停售'),'filter'=>$stop_sale_filter,'optional'=>false),
            3 => array('label'=>app::get('base')->_('非全渠道'),'filter'=>$off_omnichannel,'optional'=>false),
            4 => array('label'=>app::get('base')->_('全渠道'),'filter'=>$on_omnichannel,'optional'=>false),
        );
        
        foreach($sub_menu as $k=>$v)
        {
            $url_arr = array(
                    "app=material",
                    "ctl=admin_material_basic",
                    "act=index",
            );
            
            $url_arr[] = "view=".$k;
            if($supplier_id){
                $url_arr[] = "supplier_id=".$supplier_id;
            }
            $sub_menu[$k]['filter'] = $v['filter']?$v['filter']:null;
            $sub_menu[$k]['addon'] = $basicMaterialObj->count($v['filter']);
            $sub_menu[$k]['href'] = 'index.php?'.implode("&", $url_arr);
        }

        return $sub_menu;
    }

    /**
     * 基础物料列表项方法
     *
     * @param Post
     * @return String
     */
    function index($supplier_id=null){
        
        if($supplier_id){
            //根据供应商，获取基础物料列表
            $oSupplierGoods = app::get('purchase')->model('supplier_goods');
            $goods_id = $oSupplierGoods->getSupplierGoods($supplier_id);
            $base_filter["bm_id"] = $goods_id["goods_id"];
        }
        
        $use_buildin_export    = false;
        $use_buildin_import    = false;
        $actions               = array();
        switch($_GET['view'])
        {
            case '3':
            case '4':
                $actions    = array(
                                    array(
                                            'label' => '批量设置全渠道',
                                            'submit'=> 'index.php?app=material&ctl=admin_material_basic&act=batchUpOmnichannel&p[0]='. $_GET['view'],
                                            'target'=> 'dialog::{width:600,height:300,title:\'批量设置全渠道\'}"',
                                    ),
                                );
                break;
            default:
                $use_buildin_export    = true;
                $use_buildin_import    = true;
                $actions    = array(
                                    array(
                                        'label' => '新增',
                                        'href' => 'index.php?app=material&ctl=admin_material_basic&act=add',
                                        'target' => '_blank',
                                    ),
                                    array(
                                        'label'=>'批量设置保质期',
                                        'submit'=>"index.php?app=material&ctl=admin_material_basic&act=BatchUpExpire&p[0]=".$_GET['view'],
                                        'target'=>'dialog::{width:600,height:300,title:\'批量设置保质期\'}"',
                                    ),
                                    array(
                                        'label'=>'批量开启使用自动拆单',
                                        'submit'=>"index.php?app=material&ctl=admin_material_basic&act=BatchUpAutoSplit&p[0]=".$_GET['view'],
                                        'target'=>'dialog::{width:600,height:300,title:\'批量开启使用自动拆单\'}"'
                                    ),
                                    array(
                                        'label' => '导出模板',
                                        'href' => 'index.php?app=material&ctl=admin_material_basic&act=exportTemplate',
                                        'target' => '_blank',
                                    ),
                                    //array(
                                    //    'label' => '批量生成销售物料',
                                    //    'submit' => 'index.php?app=material&ctl=admin_material_basic&act=batchGenSalesMaterial',
                                    //    'target'=>'dialog::{width:600,height:300,title:\'批量生成销售物料\'}"',
                                    //),
                                );
        }
        
        $params = array(
            'title'=>'基础物料',
            'actions' => $actions,
            'base_filter' => $base_filter,
            'use_buildin_set_tag'=>false,
            'use_buildin_recycle'=>false,
            'use_buildin_filter'=>true,
            'use_buildin_export'=> $use_buildin_export,
            'use_buildin_import'=> $use_buildin_import,
            'finder_cols' => 'column_edit,material_name,material_bn,column_barcode,column_cost,column_weight,column_unit,column_autosplit,column_retail_price,visibled,column_specifications,column_brand,column_volume',
        );

        $this->finder('material_mdl_basic_material',$params);
    }

    /**
     * 基础物料批量导入的模板
     *
     * @param Null
     * @return String
     */
    function exportTemplate(){
        header("Content-Type: text/csv");
        header("Content-Disposition: attachment; filename=基础物料导入模板-".date('Ymd').".csv");
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        $basicMaterialObj = app::get('material')->model('basic_material');
        $title = $basicMaterialObj->exportTemplate('basicM');
        echo '"'.implode('","',$title).'"';
        
        #模板案例
        $data[0]        = array('导入普通基础物料一','maerial_001','普通','barcode_001','在售','件','150','120','500',
                                '','关闭','','','女装','黑色|155S|棉','艾莱依','开启','1','11','是');
        $data[1]        = array('导入组合基础物料二','maerial_002','组合','barcode_002','在售','件','180','135','750',
                                'product_001:2|product_002:3','开启','18','12','男装','白色|170M|棉','依视路','关闭','','','否');
        
        foreach ($data as $items)
        {
            foreach ($items as $key => $val)
            {
                $items[$key]    = kernel::single('base_charset')->utf2local($val);
            }
        
            echo "\n";
            echo '"'.implode('","',$items).'"';
        }
    }

    /**
     * 基础物料新增的展示页面方法
     *
     * @param void
     * @return void
     */
    function add(){
        /*
        $featureGrpObj = app::get('flowctrl')->model('feature_group');
        $featureGrpList = $featureGrpObj->getList('*',array(), 0, -1);
        $this->pagedata['featureGrpList'] = $featureGrpList;
        */

        #获取物料品牌
        $brand_obj = app::get('ome')->model('brand');
        $brands = $brand_obj->getList('brand_id,brand_name', array());

        #获取物料分类
        $goods_type_obj = app::get('ome')->model('goods_type');
        $goods_types = $goods_type_obj->getList('type_id,name', array());

        #第三方仓储版_隐藏保质期管理(未安装invoice并且已安装omevirtualwms) ExBOY
        $show_storage_life    = true;
        if(app::get('invoice')->is_installed() == false)
        {
            if(app::get('omevirtualwms')->is_installed())
            {
                $show_storage_life    = false;
            }
        }
        
        $this->pagedata['show_storage_life']    = $show_storage_life;
        $this->pagedata['material_brand']       =  $brands;

        $this->pagedata['goods_types'] = $goods_types;

        $envSpecConf = app::get('ome')->getConf('ome.product.serial.merge');
        $this->pagedata['envSpecConf'] = $envSpecConf;

        $this->singlepage('admin/material/basic/add.html');
    }

    /**
     * 基础物料新增提交方法
     *
     * @param Post
     * @return Boolean
     */
    function toAdd(){
        $this->begin('index.php?app=material&ctl=admin_material_basic&act=index');

        #检查数据有效性
        $checkBasicLib    = kernel::single('material_basic_check');
        $err_msg          = '';
        
        if(!$checkBasicLib->checkParams($_POST, $err_msg)){
            $this->end(false, $err_msg);
        }

        $basicMaterialObj = app::get('material')->model('basic_material');
        $basicMaterialExtObj = app::get('material')->model('basic_material_ext');
        $basicMaterialFeatureGrpObj = app::get('material')->model('basic_material_feature_group');
        $basicMaterialStockObj = app::get('material')->model('basic_material_stock');
        $basicMaterialConfObj = app::get('material')->model('basic_material_conf');
        $basicMaterialConfObjSpe = app::get('material')->model('basic_material_conf_special');
        $barocdeObj = app::get('material')->model('barcode');

        //保存物料主表信息
        $addData = array(
            'material_name' => $_POST['material_name'],
            'material_bn' => trim($_POST['material_bn']),
            'material_bn_crc32' => $_POST['material_bn_crc32'],
            'type' => $_POST['type'],
            'serial_number' => $_POST['serial_number'],
            'visibled' => $_POST['visibled'],
            'create_time' => time(),
            'omnichannel' => intval($_POST['omnichannel']),
        );
        $is_save = $basicMaterialObj->save($addData);

        if($is_save){

            //保存条码信息
            $sdf = array(
                'bm_id' => $addData['bm_id'],
                'type' => material_codebase::getBarcodeType(),
                'code' => $_POST['material_code'],
            );
            $barocdeObj->insert($sdf);

            //保存保质期配置
            $useExpireConfData = array(
                'bm_id' => $addData['bm_id'],
                'use_expire' => $_POST['use_expire'] == 1 ? 1 : 2,
                'warn_day' => $_POST['warn_day'] ?  $_POST['warn_day'] : 0,
                'quit_day' => $_POST['quit_day'] ? $_POST['quit_day'] : 0,
                'create_time' => time(),
            );
            $basicMaterialConfObj->save($useExpireConfData);

            //如果是组合物料保存相关数据
            if($addData['type'] == 2){
                $basicMaterialCombinationItemsObj = app::get('material')->model('basic_material_combination_items');
                foreach($_POST['at'] as $k=>$v){
                    $tmpChildMaterialInfo = $basicMaterialObj->dump($k, 'material_name,material_bn');

                    $addCombinationData = array(
                        'pbm_id' => $addData['bm_id'],
                        'bm_id' => $k,
                        'material_num' => $v,
                        'material_name' => $tmpChildMaterialInfo['material_name'],
                        'material_bn' => $tmpChildMaterialInfo['material_bn'],
                        'material_bn_crc32' => sprintf('%u',crc32($tmpChildMaterialInfo['material_bn'])),
                    );
                    $basicMaterialCombinationItemsObj->insert($addCombinationData);
                    $addCombinationData = null;
                }
            }

            //保存基础物料的关联的特性
            if($_POST['ftgp_id']){
                $addBindFeatureData = array(
                    'bm_id' => $addData['bm_id'],
                    'feature_group_id' => $_POST['ftgp_id'],
                );
                $basicMaterialFeatureGrpObj->insert($addBindFeatureData);
                $addBindFeatureData = null;
            }

            //保存物料扩展信息
            $addExtData = array(
                'bm_id' => $addData['bm_id'],
                'cost' => $_POST['cost'] ? $_POST['cost'] : 0.00,
                'retail_price' => $_POST['retail_price'] ? $_POST['retail_price'] : 0.00,
                'weight' => $_POST['weight'] ? $_POST['weight'] : 0.00,
                'unit' => $_POST['unit'],
                'specifications' => $_POST['material_specification'],
                'brand_id' => empty($_POST['brand']) ? 0 : $_POST['brand'],
                'cat_id' => empty($_POST['goods_type']) ? '' : $_POST['goods_type'],
                'autosplit' => empty($_POST['autosplit']) ? 'true' : $_POST['autosplit'],
                'volume' => empty($_POST['volume']) ? 0.0 : $_POST['volume'],
            );
            $basicMaterialExtObj->insert($addExtData);

            //保存物料库存信息
            $addStockData = array(
                'bm_id' => $addData['bm_id'],
                'store' => $_POST['store'] ? $_POST['store'] : 0,
                'store_freeze' => $_POST['store_freeze'] ? $_POST['store_freeze'] : 0,
            );
            $basicMaterialStockObj->insert($addStockData);

            //保存特殊扫码配置信息
            $addScanConfInfo = array(
                'bm_id' => $addData['bm_id'],
                'openscan' => $_POST['special_setting'] ? $_POST['special_setting'] : "",
                'fromposition' => $_POST['first_num'] ? $_POST['first_num'] : "",
                'toposition' => $_POST['last_num'] ? $_POST['last_num'] : "",
            );
            $basicMaterialConfObjSpe->insert($addScanConfInfo);


            $this->end(true, '操作成功');
        }else{
            $this->end(false, '保存失败');
        }

    }

    /**
     * 基础物料编辑的展示页面方法
     *
     * @param Int $bm_id
     * @return Boolean
     */
    function edit($bm_id){
        $this->begin('index.php?app=material&ctl=admin_material_basic&act=index');
        if (empty($bm_id)){
            $this->end(false,'操作出错，请重新操作');
        }

        $basicMaterialObj = app::get('material')->model('basic_material');
        $basicMaterialExtObj = app::get('material')->model('basic_material_ext');
        $basicMaterialCodeObj = app::get('material')->model('codebase');
        $basicMaterialConfObj = app::get('material')->model('basic_material_conf');
        $basicMaterialConfObjSpe = app::get('material')->model('basic_material_conf_special');
        $basicMaterialBrand = app::get('ome')->model('brand');

        $tmp_bm_id = intval($bm_id);
        $basicMaterialInfo = $basicMaterialObj->dump($tmp_bm_id);
        if(!$basicMaterialInfo){
            $this->end(false,'操作出错，请重新操作');
        }

        //检查部分按钮是否只读不可能修改
        $checkBasicLib    = kernel::single('material_basic_check');
        $readonly         = $checkBasicLib->checkEditReadOnly($bm_id);

        $basicMaterialExtInfo = $basicMaterialExtObj->dump($tmp_bm_id);
        $basicMaterialConfInfo = $basicMaterialConfObj->dump($tmp_bm_id);
        $basicMaterialBrandInfo = $basicMaterialBrand->getList('brand_id,brand_name', array());

        $material_info = array_merge($basicMaterialInfo,(array)$basicMaterialExtInfo,(array)$basicMaterialConfInfo);

        $basicBarCode = $basicMaterialCodeObj->dump(array('bm_id' => $tmp_bm_id, 'type' => material_codebase::getBarcodeType()), 'code');
        $material_info['material_cdoe'] =  empty($basicBarCode)?'':$basicBarCode['code'];

        $basicMaterialFeatureGrpObj = app::get('material')->model('basic_material_feature_group');
        $basicMaterialFeatureGrpInfo = $basicMaterialFeatureGrpObj->getList('*',array('bm_id'=>$tmp_bm_id), 0, 1);
        if($basicMaterialFeatureGrpInfo){
            $this->pagedata['bind_ftgp_id'] = $basicMaterialFeatureGrpInfo[0]['feature_group_id'];
            $this->pagedata['replacehtml'] = <<<EOF
<div id='hand-selected-product'>已选择了1个类目,<a href='javascript:void(0);' onclick='feature_group_selected_show();'>查看选中的类目.</a></div>
EOF;
        }

        $this->pagedata['material_info'] = $material_info;
        $this->pagedata['readonly'] = $readonly;

        #第三方仓储版_隐藏保质期管理(未安装invoice并且已安装omevirtualwms) ExBOY
        $show_storage_life    = true;
        if(app::get('invoice')->is_installed() == false)
        {
            if(app::get('omevirtualwms')->is_installed())
            {
                $show_storage_life    = false;
            }
        }
        $this->pagedata['show_storage_life']    = $show_storage_life;
        $this->pagedata['brand_info']           = $basicMaterialBrandInfo;

        #获取特殊配置情况
//        $envSpecConf = app::get('ome')->getConf('ome.product.serial.merge');
//        $this->pagedata['envSpecConf'] = $envSpecConf;
//        if($envSpecConf == 'special'){
        $specialConf = $basicMaterialConfObjSpe->dump($tmp_bm_id);
        $this->pagedata['specialConf'] = $specialConf;
//        }

        #获取物料分类
        $goods_type_obj = app::get('ome')->model('goods_type');
        $goods_types = $goods_type_obj->getList('type_id,name', array());
        $this->pagedata['goods_type'] = $goods_types;

        $this->singlepage('admin/material/basic/edit.html');
    }

    /**
     * 基础物料编辑提交方法
     *
     * @param Int $bm_id
     * @return Boolean
     */
    function toEdit(){
        $this->begin('index.php?app=material&ctl=admin_material_basic&act=index');

        #检查数据有效性
        $checkBasicLib    = kernel::single('material_basic_check');
        $err_msg          = '';
        $_POST['edit']    = true;//编辑标识
        
        if(!$checkBasicLib->checkParams($_POST, $err_msg)){
            $this->end(false, $err_msg);
        }

        $basicMaterialObj = app::get('material')->model('basic_material');
        $basicMaterialExtObj = app::get('material')->model('basic_material_ext');
        $basicMaterialFeatureGrpObj = app::get('material')->model('basic_material_feature_group');
        $basicMaterialStockObj = app::get('material')->model('basic_material_stock');
        $basicMaterialConfObjSpe = app::get('material')->model('basic_material_conf_special');
        $basicMaterialConfObj = app::get('material')->model('basic_material_conf');

        //更新基础物料基本信息
        $updateData['material_name'] = $_POST['material_name'];
        $updateData['type'] = $_POST['type'];
        $updateData['serial_number'] = $_POST['serial_number'];
        $updateData['visibled'] = $_POST['visibled'];
    //    $updateData['omnichannel'] = intval($_POST['omnichannel']);
        
        $filter['bm_id'] = $_POST['bm_id'];

        $is_update = $basicMaterialObj->update($updateData,$filter);
        if($is_update){
            //保存保质期配置
            $useExpireConfData = array(
                'bm_id' => $filter['bm_id'],
                'use_expire' => $_POST['use_expire'] == 1 ? 1 : 2,
                'warn_day' => $_POST['warn_day'] ?  $_POST['warn_day'] : 0,
                'quit_day' => $_POST['quit_day'] ? $_POST['quit_day'] : 0,
            );
            $basicMaterialConfObj->save($useExpireConfData);

            //如果是组合物料保存相关数据
            if($updateData['type'] == 2){
                $basicMaterialCombinationItemsObj = app::get('material')->model('basic_material_combination_items');
                //删除原有组合明细内容
                $basicMaterialCombinationItemsObj->delete(array('pbm_id'=>$filter['bm_id']));

                foreach($_POST['at'] as $k=>$v){
                    $tmpChildMaterialInfo = $basicMaterialObj->dump($k, 'material_name,material_bn');

                    $addCombinationData = array(
                        'pbm_id' => $filter['bm_id'],
                        'bm_id' => $k,
                        'material_num' => $v,
                        'material_name' => $tmpChildMaterialInfo['material_name'],
                        'material_bn' => $tmpChildMaterialInfo['material_bn'],
                        'material_bn_crc32' => sprintf('%u',crc32($tmpChildMaterialInfo['material_bn'])),
                    );
                    $basicMaterialCombinationItemsObj->insert($addCombinationData);
                    $addCombinationData = null;
                }
            }

            //删除原有的关联特性
            $basicMaterialFeatureGrpObj->delete(array('bm_id'=>$filter['bm_id']));
            //保存基础物料的关联的特性
            if($_POST['ftgp_id']){
                $addBindFeatureData = array(
                    'bm_id' => $filter['bm_id'],
                    'feature_group_id' => $_POST['ftgp_id'],
                );
                $basicMaterialFeatureGrpObj->insert($addBindFeatureData);
                $addBindFeatureData = null;
            }

            //保存物料扩展信息
            $updateExtData = array(
                'cost' => $_POST['cost'] ? $_POST['cost'] : 0.00,
                'retail_price' => $_POST['retail_price'] ? $_POST['retail_price'] : 0.00,
                'weight' => $_POST['weight'] ? $_POST['weight'] : 0.00,
                'unit' => $_POST['unit'],
                'specifications' => $_POST['material_specification'],
                'brand_id' => empty($_POST['brand']) ? 0 : $_POST['brand'],
                'cat_id' => empty($_POST['goods_type']) ? 0 : $_POST['goods_type'],
                'autosplit' => empty($_POST['autosplit']) ? 'true' : $_POST['autosplit'],
                'volume' => empty($_POST['volume']) ? 0.0 : $_POST['volume'],
            );
            $basicMaterialExtObj->update($updateExtData, $filter);

            //保存扫码配置信息
            $addScanConfInfo = array(
                'openscan' => $_POST['special_setting'] ? $_POST['special_setting']: '',
                'fromposition' => $_POST['first_num'] ? $_POST['first_num'] : '',
                'toposition' => intval($_POST['last_num']) ? intval($_POST['last_num']) : 0,
            );
            $basicMaterialConfObjSpe->update($addScanConfInfo, $filter);
            //更新物料同步信息

            app::get('console')->model('foreign_sku')->update_status($filter['bm_id']);
            $this->end(true, '保存成功');
        }else{
            $this->end(false, '保存失败');
        }

    }

    /**
     * 基础物料列表弹窗数据获取方法
     *
     * @param Void
     * @return String
     */
    function findMaterial($supplier_id=null)
    {
        $basicMaterialSelect    = kernel::single('material_basic_select');#基础物料 ExBOY

        #供应商频道
        if ($supplier_id)
        {
            //根据供应商商品
            $oSupplierGoods = app::get('purchase')->model('supplier_goods');

            $supplier_goods = $oSupplierGoods->getSupplierGoods($supplier_id);

            $products    = $basicMaterialSelect->getlist('bm_id', array('bm_id'=>$supplier_goods['goods_id']));

            $product_list = array();
            if ($products)
                foreach ($products as $k=>$v){
                    $product_list[] = $v['product_id'];
                }

            $base_filter['bm_id']    = $product_list;
        }

        //只能选择可见的物料作为组合的明细内容
        $base_filter['visibled'] = 1;

        if($_GET['type'] == 1){
            $base_filter['type'] = 1;
        }

        $params = array(
            'title'=>'基础物料列表',
            'use_buildin_new_dialog' => false,
            'use_buildin_set_tag'=>false,
            'use_buildin_recycle'=>false,
            'use_buildin_export'=>false,
            'use_buildin_import'=>false,
            'use_buildin_filter'=>true,
            'base_filter' => $base_filter,
        );
        $this->finder('material_mdl_basic_material', $params);
    }

    /**
     * 基础物料列表弹窗选中物料信息查询方法
     *
     * @param Int $bm_id
     * @return String
     */
    function getMaterial(){
        $bm_id = $_POST['bm_id'];
        $material_bn= $_GET['material_bn'];
        $material_name= $_GET['material_name'];

        if (is_array($bm_id)){
            if ($bm_id[0] == "_ALL_"){
                $filter = '';
            }else {
                $filter['bm_id'] = $bm_id;
            }
        }

        if($material_bn){
            $filter = array(
                'material_bn'=>$material_bn
            );
        }

        if($material_name){
            $filter = array(
                'material_name'=>$material_name
            );
        }

        $basicMaterialObj = app::get('material')->model('basic_material');
        $filter['use_like'] = 1;
        $data = $basicMaterialObj->getList('bm_id,material_name,material_bn',$filter,0,-1);

        if (!empty($data)){
            foreach ($data as $k => $item){
                $item['num'] = null;
                $item['rate'] = 0;
                $rows[] = $item;
            }
        }

        echo json_encode($rows);
    }

    /**
     * 基础物料组合信息异步加载方法
     *
     * @param Int $bm_id
     * @return String
     */
    function getEditMaterial($bm_id){
        if ($bm_id == ''){
            $bm_id = $_POST['p[0]'];
        }

        $basicMaterialObj = app::get('material')->model('basic_material');
        $basicMaterialCombinationItemsObj = app::get('material')->model('basic_material_combination_items');

        $rows = array();
        $items = $basicMaterialCombinationItemsObj->getList('bm_id,material_bn,material_name,material_num',array('pbm_id'=>$bm_id),0,-1);

        echo json_encode($items);
    }

    /**
     * 基础物料组合信息异步加载方法
     *
     * @param Int $bm_id
     * @return String
     */
    function batchGenSalesMaterial(){
        $this->_request = kernel::single('base_component_request');
        $material_info = $this->_request->get_post();

        if(!isset($material_info['isSelectedAll']) && empty($material_info['bm_id'])){
            $error_msg = '请选择要生成销售物料的基础物料';
        }else{
            $lastBatchGenSalesMaterial = app::get('material')->getConf('lastBatchGenSalesMaterial'); //上次执行批量生成销售物料的时间
            $getMaterialIntervalTime = 5;

            if(($lastBatchGenSalesMaterial['execTime']+60*$getMaterialIntervalTime)<time()){
                $this->pagedata['is_allow'] = true;
            }else{
                $this->pagedata['is_allow'] = false;
            }
        }

        $basicMaterialObj = app::get('material')->model('basic_material');
        if(isset($material_info['isSelectedAll'])){
            unset($material_info['isSelectedAll']);
        }

        $materialList =$basicMaterialObj->getList('bm_id',$material_info, 0, -1);
        /*
        $count = 0;
        $i = 0;
        $materialGroup = array();
        foreach($materialList as $k => $material){
            if($count == 10){
                $count = 0;
                $i++;
            }

            $materialGroup[$i]['materials'] .= $material['bm_id'].",";

            $count++;
        }
        */

        $this->pagedata['materialCnt'] = count($materialList);
        $this->pagedata['materialGroup'] = json_encode($materialList);

        $this->pagedata['bm_id'] = serialize($material_info['bm_id']);

        $this->pagedata['lastBatchGenSalesMaterial'] = !empty($lastBatchGenSalesMaterial['execTime']) ? date('Y-m-d H:i:s',$lastBatchGenSalesMaterial['execTime']) : '';
        $this->pagedata['getMaterialIntervalTime'] = $getMaterialIntervalTime;
        $this->pagedata['currentTime'] = time();

        $this->display('admin/material/basic/gensalesmaterial.html');
    }

    function dobatchGen(){
        //传入的物料格式 id1,id2,id3,一次10个,页面js变量控制
        $params = $_POST['ajaxParams'];
        if (empty($params)) {
            echo $this->_ajaxRespone();
            exit;
        }

        /* 执行时间判断 start */
        $pageBn = intval($_POST['pageBn']);
        $lastBatchGenSalesMaterial = app::get('material')->getConf('lastBatchGenSalesMaterial'); //上次获取订单信息(key为execTime表示执行时间，key为pageBn表示页面编号),
        $getMaterialIntervalTime = 5;

        if($pageBn !=$lastBatchGenSalesMaterial['pageBn'] && ($lastBatchGenSalesMaterial['execTime']+60*$getMaterialIntervalTime)>time()){
            echo $this->_ajaxRespone();
            exit;
        }
        if($pageBn !=$lastBatchGenSalesMaterial['pageBn'] && $pageBn<$lastBatchGenSalesMaterial['execTime']){
            echo $this->_ajaxRespone();
            exit;
        }

        //记录本次获取订单时间
        $currentGetOrder = array(
            'execTime'=>time(),
            'pageBn'=>$pageBn,
        );
        app::get('material')->setConf('lastBatchGenSalesMaterial',$currentGetOrder);
        /* 执行时间判断 end */

        //基础物料转成销售处理
        $result = kernel::single('material_basic_exchange')->process($params);
        echo $this->_ajaxRespone($result);
    }

    /**
     *  对输入的内容进行格式化输出至AJAX
     *
     * @author hzjsq (2011/3/24)
     * @param Mixed $param 要转换的内容
     * @return String
     */
    private function _ajaxRespone($param) {

        if (empty($param)) {

            return json_encode(array('total' => 0, 'succ' => 0, 'fail' => 0));
        } else {

            return json_encode($param);
        }
    }

    /**
     * @description 显示关联的物料
     * @access public
     * @param void
     * @return void
     */
    public function showMaterialBase()
    {
        $bm_id = kernel::single('base_component_request')->get_post('bm_id');

        if ($bm_id)
        {
            #前端店铺_规则应用传值 ExBOY
            if(!is_array($bm_id))
            {
                $bm_id    = explode(',', $bm_id);
            }

            $this->pagedata['_input'] = array(
                'name' => 'bm_id',
                'idcol' => 'bm_id',
                '_textcol' => 'material_name',
            );

            $basicMaterialObj = app::get('material')->model('basic_material');
            $list = $basicMaterialObj->getList('bm_id,material_name', array('bm_id'=>$bm_id, 'visibled'=>1),0,-1,'bm_id asc');
            $this->pagedata['_input']['items'] = $list;
        }

        $this->display('admin/material/basic/show_material_base.html');
    }

    /**
     * @description 显示绑定的特性
     * @access public
     * @param void
     * @return void
     */
    public function showFeatureGrp()
    {
        $ftgp_id = kernel::single('base_component_request')->get_post('ftgp_id');

        if ($ftgp_id)
        {
            $this->pagedata['_input'] = array(
                'name' => 'ftgp_id',
                'idcol' => 'ftgp_id',
                '_textcol' => 'ftgp_name',
            );

            /*
            $featureGrpObj = app::get('flowctrl')->model('feature_group');
            $list = $featureGrpObj->getList('ftgp_id,ftgp_name', array('ftgp_id'=>$ftgp_id),0,-1,'ftgp_id asc');
            $this->pagedata['_input']['items'] = $list;
            */
        }

        $this->display('admin/material/basic/show_feature_group.html');
    }

    /**
     * @description 批量设置保质期配置的页面
     * @access public
     * @param void
     * @return void
     */
    public function BatchUpExpire($view){

        $sub_menu = $this->_views();
        foreach ($sub_menu as $key => $value) {
            if($key == $view){
                $base_filter = $value['filter'];
            }
        }

        $filter = array_merge((array)$_POST,(array)$base_filter);
        $basicMaterialObj = app::get('material')->model('basic_material');
        $basicMaterialObj->filter_use_like = true;
        $count = $basicMaterialObj->count($filter);

        $this->pagedata['total'] = $count;
        $this->pagedata['filter'] = http_build_query($filter);
        $this->display('admin/material/basic/batch_update_expire.html');
    }

    /**
     * @description 设置保质期
     * @access public
     * @param array $_POST
     * @return void
     */
    function doBatchUpExpire(){
        
        $checkBasicLib    = kernel::single('material_basic_check');
        
        $page_no = intval($_GET['page_no']) ? intval($_GET['page_no']) : 1;
        $page_size = 10;
        $offset = ($page_no-1)*$page_size;
        $total = intval($_GET['total']);
        parse_str($_POST['filter'],$filter);

        $basicMaterialObj = app::get('material')->model('basic_material');
        $basicMaterialObj->filter_use_like = true;
        $materialList = $basicMaterialObj->getList('*',$filter,$offset,$page_size);
        $succ_num = $fail_num = 0;
        if ($materialList) {
            foreach ((array) $materialList as $material_info) {
                
                #如果有批次明细 或者 采购明细 就不能变更保质期的开关
                $readonly    = $checkBasicLib->checkEditReadOnly($material_info['bm_id']);
                if($readonly['use_expire'])
                {
                    $fail_num++;
                }
                else 
                {
                    $arr_bm_id[] = $material_info['bm_id'];
                }
            }
            $succ_num = count($materialList)-$fail_num;

            if($arr_bm_id){
                //如果有批次明细就不能变更保质期的开关
                /**
                $basicMaterialStorageLifeObj = app::get('material')->model('basic_material_storage_life');
                $expireItemsInfo = $basicMaterialStorageLifeObj->getList('distinct bm_id',array('bm_id'=>$arr_bm_id));
                if($expireItemsInfo){
                    foreach($expireItemsInfo as $expireItem){
                        $flag = array_search($expireItem['bm_id'], $arr_bm_id);
                        if($flag >=0){
                            unset($arr_bm_id[$flag]);
                            $fail_num++;
                        }
                    }
                    $succ_num = count($materialList)-$fail_num;
                }else{
                    $succ_num = count($materialList);
                }
                */

                $basicMaterialConfObj = app::get('material')->model('basic_material_conf');
                $updateData = array(
                    'use_expire' => $_POST['use_expire'] == 1 ? 1 : 2,
                    'warn_day' => $_POST['warn_day'] ? $_POST['warn_day'] : 0,
                    'quit_day' => $_POST['quit_day'] ? $_POST['quit_day'] : 0,
                );
                $basicMaterialConfObj->update($updateData, array('bm_id'=>$arr_bm_id));
            }
        }

        $result = array('status'=>'running','data'=>array('succ_num'=>$succ_num,'fail_num'=>$fail_num));

        if ( ($page_size * $page_no) >= $total) {
            $result['status'] = 'complete';
            $result['data']['rate'] = '100';
        } else {
            $result['data']['rate'] =  $page_no * $page_size / $total * 100;
        }

        echo json_encode($result);exit;
    }
    
    /**
     * 批量设置全渠道页面
     */
    public function batchUpOmnichannel($view)
    {
        $sub_menu    = $this->_views();
        foreach ($sub_menu as $key => $value) {
            if($key == $view){
                $base_filter    = $value['filter'];
            }
        }
        
        $base_filter    = array('omnichannel'=> $base_filter['omnichannel']);
        $filter         = array_merge((array)$_POST, (array)$base_filter);
        
        $basicMaterialObj    = app::get('material')->model('basic_material');
        $basicMaterialObj->filter_use_like = true;
        
        $count    = $basicMaterialObj->count($filter);
        
        $this->pagedata['total'] = $count;
        $this->pagedata['filter'] = http_build_query($filter);
        
        $this->display('admin/material/basic/batch_set_omnichannel.html');
    }
    
    /**
     * 批量设置全渠道
     */
    function doBatchUpOmnichannel()
    {
        $page_no    = intval($_GET['page_no']) ? intval($_GET['page_no']) : 1;
        $page_size  = 10;
        $offset     = ($page_no-1) * $page_size;
        $total      = intval($_GET['total']);
        
        parse_str($_POST['filter'], $filter);
        
        $omnichannel    = ($_POST['omnichannel'] == 1 ? 1 : 2);
        
        $basicMaterialObj = app::get('material')->model('basic_material');
        $basicMaterialObj->filter_use_like = true;
        $materialList = $basicMaterialObj->getList('bm_id, omnichannel', $filter, $offset, $page_size);
        $succ_num = $fail_num = 0;
        
        if ($materialList)
        {
            foreach ($materialList as $material_info)
            {
                $arr_bm_id[]    = $material_info['bm_id'];
                
                $succ_num++;
            }
            
            if($arr_bm_id)
            {
                $basicMaterialObj->update(array('omnichannel'=>$omnichannel), array('bm_id'=>$arr_bm_id));
            }
        }
        
        $fail_num  = count($materialList) - $succ_num;
        $result    = array('status'=>'running','data'=>array('succ_num'=>$succ_num, 'fail_num'=>$fail_num));
        
        if ( ($page_size * $page_no) >= $total)
        {
            $result['status']        = 'complete';
            $result['data']['rate']  = '100';
        } else {
            $result['data']['rate']  =  $page_no * $page_size / $total * 100;
        }
        
        echo json_encode($result);
        exit; 
    }

    /**
     * @description 批量开启使用自动拆单
     * @access public
     * @param void
     * @return void
     */
    public function BatchUpAutoSplit($view){

        $sub_menu = $this->_views();
        foreach ($sub_menu as $key => $value) {
            if($key == $view){
                $base_filter = $value['filter'];
            }
        }

        $filter = array_merge((array)$_POST,(array)$base_filter);
        $basicMaterialObj = app::get('material')->model('basic_material');
        $basicMaterialObj->filter_use_like = true;
        $count = $basicMaterialObj->count($filter);

        $this->pagedata['total'] = $count;
        $this->pagedata['filter'] = http_build_query($filter);
        $this->display('admin/material/basic/batch_update_autosplit.html');
    }

    /**
     * @description 设置是否自动拆单
     * @access public
     * @param array $_POST
     * @return void
     */
    function doBatchUpAutoSplit(){

        $page_no = intval($_GET['page_no']) ? intval($_GET['page_no']) : 1;
        $page_size = 10;
        $offset = ($page_no-1)*$page_size;
        $total = intval($_GET['total']);
        parse_str($_POST['filter'],$filter);

        $basicMaterialObj = app::get('material')->model('basic_material');
        $basicMaterialObj->filter_use_like = true;
        $materialList = $basicMaterialObj->getList('*',$filter,$offset,$page_size);
        $succ_num = $fail_num = 0;
        if ($materialList) {
            foreach ((array) $materialList as $material_info) {
                $arr_bm_id[] = $material_info['bm_id'];
            }
            if($arr_bm_id){
                $basicMaterialExtObj = app::get('material')->model('basic_material_ext');
                $updateData = array(
                    'autosplit'=> in_array($_POST['autosplit'], array('true', 'false')) ? $_POST['autosplit'] : 'true'
                );
                $bool = $basicMaterialExtObj->update($updateData, array('bm_id'=>$arr_bm_id));
                if(!$bool){
                    $fail_num++;
                }
            }
            $succ_num = count($materialList) - $fail_num;
        }

        $result = array('status'=>'running','data'=>array('succ_num'=>$succ_num,'fail_num'=>$fail_num));

        if ( ($page_size * $page_no) >= $total) {
            $result['status'] = 'complete';
            $result['data']['rate'] = '100';
        } else {
            $result['data']['rate'] =  $page_no * $page_size / $total * 100;
        }

        echo json_encode($result);exit;
    }
}
